const app = require("express").Router();
const { Comment, Users } = require("../model/index");

// 查询用户状态根据类型
app.get("/getUserStatusByType", (req, res) => {
  const { type, userid } = req.query;
  if (!type) {
    res.send({ code: -1, msg: "没有类型" });
  }
  if (!userid) {
    res.send({ code: -1, msg: "用户id不能为空" });
  }
  Users.findAndCountAll({
    attributes:[type],
    where: {
      userid,
    },
  }).then((ret) => {
    if (ret && ret.rows[0]) {
      res.send({ code: 0, data: ret.rows[0] });
    } else {
      res.send({ code: -1, msg: "查询失败" });
    }
  });
});

app.post("/addcomment", (req, res) => {
  let data = req.body;
  if (!data.username) {
    res.send({ code: -1, msg: "用户名未传" });
  }
  if (!data.userid) {
    res.send({ code: -1, msg: "用户名id未传" });
  }
  if (!data.content) {
    res.send({ code: -1, msg: "请输入内容" });
  }
  if (!data.publicid) {
    res.send({ code: -1, msg: "请输入publicid" });
  }
  Comment.create(data).then((ret) => {
    if (ret) {
      res.send({ code: 0, data: ret });
    } else {
      res.send({ code: -1, msg: "评论失败" });
    }
  });
});

app.get("/commentlist", (req, res) => {
  console.log(req.query,'publicidpublicidpublicid')

  const { page, publicid } = req.query;
  let offset = (page - 1) * 10;
  if (!page) {
    res.send({ code: -1, msg: "页码未传" });
    return;
  }
  if (!publicid) {
    res.send({ code: -1, msg: "publicid未传" });
    return;
  }
  let where = null;
  where = {
    publicid,
  };
  Comment.findAndCountAll({
    order: [['createDate', 'DESC']],
    limit: 100,
    offset,
    where,
  }).then((ret) => {
    if (ret) {
      res.send({ code: 0, data: ret });
    } else {
      res.send({ code: -1, msg: "查找失败" });
    }
  });
});

module.exports = app;
